package com.example.springboot0507.service;

import com.example.springboot0507.dao.UserDao;
import com.example.springboot0507.dao.UserRepository;
import com.example.springboot0507.entity.User;
import com.example.springboot0507.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author 王博
 * @DateTime 2025-05-15 08:34
 */
@Service
@Slf4j
public class UserService {
    @Resource
    private UserRepository userRepository;
    @Resource
    private UserDao userDao;
    @Resource
    private SqlSessionFactory sqlSessionFactory;

    @Transactional(rollbackFor = Exception.class)
    @CachePut(value = "redisCache", key = "'user_id:'+#result.id")
    public User save(User user) {
        User dbUser = userRepository.save(user);
        log.info("保存的用户的id为:{}", dbUser.getId());
        return dbUser;
    }

    public List<User> getList(){
        log.info("{}",sqlSessionFactory);
        return userDao.getList();
    }

    @Cacheable(value = "redisCache", key = "'user_id:'+#id")
    public User getById(Long id){
        return userRepository.findById(id).orElseThrow(()->new ServiceException("id传递错误"));
    }
}
